@page "/preferences"
@attribute [Authorize]
@using System.Text.Json;
@using System.Text;
@using System.Net.Http.Headers;

@inject NavigationManager Navigation
@inject IAccessTokenProvider AccessTokenProvider

<p>User preferences</p>

<input id="color-preference" type="text" @bind="Color" />
<button id="submit-preference" @onclick="SendPreferences">Send</button>

@code {
    public string Color { get; set; }

    public async Task SendPreferences()
    {
        var content = new StringContent(JsonSerializer.Serialize(new UserPreferences { Color = Color }), Encoding.UTF8, "application/json");
        var tokenResponse = await AccessTokenProvider.RequestAccessToken();
        if (tokenResponse.TryGetToken(out var token))
        {
            var client = new HttpClient { BaseAddress = new Uri(Navigation.BaseUri) };
            var request = new HttpRequestMessage(HttpMethod.Post, "Preferences/AddPreferences");
            request.Content = content;

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Value);

            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var query = new Uri(Navigation.Uri).Query;
                var hasReturnUrl = System.Text.RegularExpressions.Regex.Match(query, ".*?returnUrl=([^&]+).*");
                if (hasReturnUrl.Success)
                {
                    var returnUrl = hasReturnUrl.Groups[1];
                    Navigation.NavigateTo(Uri.UnescapeDataString(returnUrl.Value));
                }
            }
            else
            {
                Navigation.NavigateTo("/");
            }
        }
    }
}
